from app.models.user import User, UserLogin
from app import db

class UserFunc(User):

	@classmethod
	def chinese_name(cls):
		return "用户"

	@property
	def small_allow_list(self):
		return ["id", "name", "avatar_image_url"]

	@classmethod
	def available(cls):
		return cls.query.filter(cls.is_delete!=True)

	@classmethod
	def register(cls, unique_id, login_type, password):
		md5_password = cls.md5_cypt(password)
		u = User(name=unique_id, md5_password=md5_password)
		db.session.add(u)
		db.session.flush()
		l = UserLogin(unique_id=unique_id, login_type=login_type, user_id=u.id)
		db.session.add(l)
		try:
			db.session.commit()
			return True, u.id
		except Exception as e:
			db.session.rollback()
			return False, "注册失败"

	@classmethod
	def login(cls, unique_id, password):
		ul = UserLogin.available().filter_by(unique_id=unique_id).first()
		user = cls.get_object_by_id(ul.user_id)
		if cls.md5_cypt(password) == user.md5_password:
			return True, user.to_dict(method="small")
		else:
			return False, "登录失败"


	@classmethod
	def md5_cypt(cls, password):
		import hashlib, hmac
		mac = hmac.new(b'key', password.encode(encoding='utf-8'), hashlib.md5) 
		mac.digest()
		res = mac.hexdigest()
		return res

	@classmethod
	def check_unique_id(cls, value):
		ul = UserLogin.available().filter_by(unique_id=value).first()
		return value

	def _to_dict(self):
		res = {}
		res.update(self.__dict__)
		if "_sa_instance_state" in res:
			del res['_sa_instance_state']
		if "birthdate" in res and res["birthdate"] is not None:
			res["birthdate"] = self.birthdate.strftime("%Y-%m-%d %H:%M:%S")
		if "avatar_image_url" in res and res["avatar_image_url"] is None:
			res["avatar_image_url"] = "https://dongdong-bucket.oss-cn-beijing.aliyuncs.com/web/images/avatar.jpg"
		del res["created_at"]
		del res["updated_at"]
		return res
